<?php
if(!isset($_SESSION)) session_start();

function show_form ($id) {
    
echo <<<STOP
    
<form enctype="multipart/form-data"  action="upload_image.php" method="POST">

<input name="file{$id}" type="file" style="float:left" />
<input style="float:left" type="submit" value="Upload" />
</form>
    
STOP;
}

if (isset($_REQUEST["id"])) {
    $id=$_REQUEST["id"];
   
 
    
    show_form($id);
   
} else {

    $module = "{$_SERVER["DOCUMENT_ROOT"]}/modules/news/banners/";
    $dirhandler = opendir($module);
    $nofiles=1;
    $pic_types = array("jpg", "jpeg", "gif", "png");
    while ($file = readdir($dirhandler)) {
        if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$pic_types)) {
            $files[$nofiles]=$file;
            $nofiles++;
        }  
    }
    //print_r ($files);
    
    
    for ($i=1;$i<=4;$i++) {
        if (isset ($_FILES["file{$i}"])) {
            
            $target_path = "$module";
            if (!is_dir($target_path)) mkdir ($target_path, 0 , true);

            $target_path = $target_path . basename( $_FILES["file{$i}"]['name']); 

            if(move_uploaded_file($_FILES["file{$i}"]['tmp_name'], $target_path)) {
                //echo "Image {$i} {$files[$i]} &rarr; {$_FILES["file{$i}"]["name"]}";
                unlink ("{$module}{$files[$i]}");
                echo "<img style=\"width:37%\"src=/modules/news/banners/" . basename( $_FILES["file{$i}"]['name']) . ">";
                //show_form ($i);
            } else{
                echo "<script type=\"text/javascript\">alert(\"There was an error uploading the file, please try again!\")</script>";
                show_form ($i);
            }
        }
    }
}
?>
